package cn.exrick.xboot.modules.activiti.controller.business;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Map;

import org.jxls.area.Area;
import org.jxls.builder.AreaBuilder;
import org.jxls.builder.xml.XmlAreaBuilder;
import org.jxls.common.CellRef;
import org.jxls.common.Context;
import org.jxls.transform.Transformer;
import org.jxls.util.TransformerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.gson.Gson;

import cn.exrick.xboot.common.constant.CommonConstant;
import cn.exrick.xboot.common.constant.SettingConstant;
import cn.exrick.xboot.common.utils.CommonUtil;
import cn.exrick.xboot.common.utils.PageUtil;
import cn.exrick.xboot.common.utils.ResultUtil;
import cn.exrick.xboot.common.vo.PageVo;
import cn.exrick.xboot.common.vo.Result;
import cn.exrick.xboot.common.vo.SearchVo;
import cn.exrick.xboot.modules.activiti.entity.business.MatterAnalysis;
import cn.exrick.xboot.modules.activiti.service.business.MatterAnalysisService;
import cn.exrick.xboot.modules.base.service.SettingService;
import cn.exrick.xboot.modules.base.vo.OssSetting;
import cn.exrick.xboot.modules.file.entity.File;
import cn.exrick.xboot.modules.file.manage.FileManageFactory;
import cn.exrick.xboot.modules.file.service.FileService;
import cn.hutool.core.date.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * @author lihuan
 */
@Slf4j
@RestController
@Api(description = "数据统计接口")
@RequestMapping("/xboot/analysis")
@Transactional
public class AnalysisController {

	@Autowired
	private FileService fileService;
	@Autowired
	private SettingService settingService;
	@Autowired
	private FileManageFactory fileManageFactory;
	@Autowired
	private MatterAnalysisService matterAnalysisService;

	@RequestMapping(value = "/serviceSection", method = RequestMethod.GET)
	@ApiOperation(value = "便名服务科统计")
	public Result<IPage<MatterAnalysis>> analysis1(String deptId, @ModelAttribute SearchVo searchVo,
			@ModelAttribute PageVo pageVo) {
		IPage<MatterAnalysis> page = matterAnalysisService.analysis1(PageUtil.initMpPage(pageVo), searchVo, deptId);
		return new ResultUtil<IPage<MatterAnalysis>>().setData(page);
	}

	@RequestMapping(value = "/department", method = RequestMethod.GET)
	@ApiOperation(value = "承办部门统计")
	public Result<IPage<MatterAnalysis>> analysis2(String deptId, @ModelAttribute SearchVo searchVo,
			@ModelAttribute PageVo pageVo) {
		IPage<MatterAnalysis> page = matterAnalysisService.analysis2(PageUtil.initMpPage(pageVo), searchVo, deptId);
		return new ResultUtil<IPage<MatterAnalysis>>().setData(page);
	}

	@RequestMapping(value = "/problemType", method = RequestMethod.GET)
	@ApiOperation(value = "问题分类统计")
	public Result<IPage<MatterAnalysis>> analysis3(String typeId, @ModelAttribute SearchVo searchVo,
			@ModelAttribute PageVo pageVo) {
		IPage<MatterAnalysis> page = matterAnalysisService.analysis3(PageUtil.initMpPage(pageVo), searchVo, typeId);
		return new ResultUtil<IPage<MatterAnalysis>>().setData(page);
	}

	@PostMapping(value = "/serviceSection/exportEXCEL")
	public Result<Object> exportEXCEL1(String deptId, @ModelAttribute SearchVo searchVo, @ModelAttribute PageVo pageVo)
			throws IOException, URISyntaxException {
		pageVo.setPageSize(99999);
		IPage<MatterAnalysis> pages = this.matterAnalysisService.analysis1(PageUtil.initMpPage(pageVo), searchVo,
				deptId);
		String result = generatorExcel(pages.getRecords(), "便民服务科统计");
		return new ResultUtil<Object>().setData(result);
	}

	@PostMapping(value = "/department/exportEXCEL")
	public Result<Object> exportEXCEL2(String deptId, @ModelAttribute SearchVo searchVo, @ModelAttribute PageVo pageVo)
			throws IOException, URISyntaxException {
		pageVo.setPageSize(99999);
		IPage<MatterAnalysis> pages = this.matterAnalysisService.analysis2(PageUtil.initMpPage(pageVo), searchVo,
				deptId);
		String result = generatorExcel(pages.getRecords(), "承办部门统计");
		return new ResultUtil<Object>().setData(result);
	}

	@PostMapping(value = "/problemType/exportEXCEL")
	public Result<Object> exportEXCEL3(String typeId, @ModelAttribute SearchVo searchVo, @ModelAttribute PageVo pageVo)
			throws IOException, URISyntaxException {
		pageVo.setPageSize(99999);
		IPage<MatterAnalysis> pages = this.matterAnalysisService.analysis3(PageUtil.initMpPage(pageVo), searchVo,
				typeId);
		String result = generatorExcel(pages.getRecords(), "问题分类统计");
		return new ResultUtil<Object>().setData(result);
	}

	private String generatorExcel(List<?> records, String filename) throws IOException {
		String template, templateConfig;
		if (filename.equals("便民服务科统计")) {
			template = "template/ServiceSectionTemplate.xls";
			templateConfig = "template/ServiceSectionConfig.xml";
		} else if (filename.equals("承办部门统计")) {
			template = "template/DeptTemplate.xls";
			templateConfig = "template/DeptConfig.xml";
		} else if (filename.equals("问题分类统计")) {
			template = "template/ProblemTypeTemplate.xls";
			templateConfig = "template/ProblemTypeConfig.xml";
		} else { 
			return "";
		}
		String fKey = CommonUtil.renamePic(".xls");
		String result = fileManageFactory.getFileManage(CommonConstant.OSS_LOCAL).pathUpload("", fKey);
		try (InputStream is = this.getClass().getResourceAsStream("/" + template)) {
			try (OutputStream os = new FileOutputStream(result)) {
				Transformer transformer = TransformerFactory.createTransformer(is, os);
				try (InputStream configInputStream = this.getClass().getResourceAsStream("/" + templateConfig)) {
					AreaBuilder areaBuilder = new XmlAreaBuilder(configInputStream, transformer);
					List<Area> xlsAreaList = areaBuilder.build();
					Area xlsArea = xlsAreaList.get(0);
					Context context = new Context();
					context.putVar("Cld", records);
					xlsArea.applyAt(new CellRef("Result!A1"), context);
					transformer.write();
				}
			}
		}

		java.io.File file = new java.io.File(result);
		File f = new File();
		f.setLocation(CommonConstant.OSS_LOCAL);
		// 保存数据信息至数据库
		String day = DateUtil.format(DateUtil.date(), "yyyyMMdd");
		f.setName(filename + "_" + day + ".xls");
		f.setSize(file.length());
		f.setFKey(fKey);
		f.setUrl(result);
		fileService.save(f);
		OssSetting os = new Gson().fromJson(settingService.get(SettingConstant.LOCAL_OSS).getValue(), OssSetting.class);
		result = os.getHttp() + os.getEndpoint() + "/" + f.getId() + "?byFilename=true";
		return result;
	}

    @RequestMapping(value = "/matter/type/getAll", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取全部类型数据")
    public Result<List<Map<String, String>>> getAll(){
        List<Map<String, String>> list = matterAnalysisService.getAllMatterType();
        return new ResultUtil<List<Map<String, String>>>().setData(list);
    }
    
//    @GetMapping("load/{uuid}")
//    public void  load(@PathVariable String uuid, HttpServletResponse response) throws IOException {
//        System.out.println(uuid);
//        byte[] bytes = Files.readAllBytes(Paths.get(orderConfig.getTarPath()+uuid+".xls"));
//        response.reset();
//        response.setHeader("Content-Disposition", String.format("attachment; filename=%s.xls", uuid));
//        response.addHeader("Content-Length", "" + bytes.length);
//        response.setContentType("application/octet-stream; charset=UTF-8");
//        IoUtil.write(response.getOutputStream(), Boolean.TRUE, bytes);
//    }
//
//    @GetMapping("load2/{fileName}")
//    public void  load2(@PathVariable String fileName, HttpServletResponse response) throws IOException {
//        byte[] bytes = Files.readAllBytes(Paths.get(orderConfig.getTarPath()+fileName));
//        response.reset();
//        response.setHeader("Content-Disposition", String.format("attachment; filename=%s.doc", fileName));
//        response.addHeader("Content-Length", "" + bytes.length);
//        response.setContentType("application/octet-stream; charset=UTF-8");
//        IoUtil.write(response.getOutputStream(), Boolean.TRUE, bytes);
//    }
//    /**
//     * 处理单位
//     * @return
//     */
//    @PostMapping("/cldw")
//    public List<Map> cldw() {
//        return  this.cldMapper.cldw();
//    }

}
